<?php
/**
 * redis操作类
 * User: Administrator
 * Date: 2018/7/27
 * Time: 14:01
 */

namespace app\common\lib\redis;

class Predis
{
    public $redis = "";
    /**
     * @var null 定义单例模式的变量
     */
    private static $_instance = null;

    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct()
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeOut'));

        if ($result == false) {
            throw new \Exception('redis connect error');
        }
    }

    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0)
    {
        if (!$key) {
            return '';
        }
        if (is_array($value)) {
            $value = json_encode($value);
        }
        if ($time == 0) {
            echo 'time = 0';
            return $this->redis->set($key, $value);
        }
        return $this->redis->set($key, $value, $time);
    }

    /**
     * get
     * @param $key
     * @return bool|string
     */
    public function get($key)
    {
        if (!$key) {
            return '';
        }
        return $this->redis->get($key);
    }

    /**
     * delete
     * @param $key
     * @return int|string
     */
    public function del($key)
    {

        if (!$key) {
            return '';
        }
        return $this->redis->del($key);
    }

    /**
     * 有序集合存放数据
     * @param $key
     * @param $value
     * @return mixed
     */
    public function sAdd($key, $value)
    {
        return $this->redis->sAdd($key, $value);
    }

    /**
     * 删除有序集合里的值
     * @param $key
     * @param $value
     * @return int
     */
    public function sRem($key, $value)
    {
        return $this->redis->sRem($key, $value);
    }

    /**
     * 获取有序合集里的数据
     * @param $key
     * @return mixed
     */
    public function sMembers($key) {
        return $this->redis->sMembers($key);
    }

    /**
     * 魔法函数实现精简代码
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments)
    {
        if (count($arguments) != 2) {
            return [];
        }
        return $this->redis->$name($arguments[0],$arguments[1]);
    }
}